package soft.quicknote;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;

import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;

import java.sql.Timestamp;
import java.util.ArrayList;

import soft.quicknote.beans.Note;

public class QueryUtil {

    public static ArrayList<Note> queryNoteFromTitle(DBHelper helper, String query) {

        SQLiteDatabase db = helper.getReadableDatabase();
        query = "%" + query + "%";
        Cursor cursor = db.rawQuery("SELECT * FROM " + DBHelper.NOTE_TABLE + " WHERE title LIKE ?", new String[]{query});
        ArrayList<Note> res = fetchAllNote(cursor);
        cursor.close();
        db.close();
        return res;
    }

    public static ArrayList<Note> queryNoteFromContent(DBHelper helper, String query) {
        SQLiteDatabase db = helper.getReadableDatabase();
        query = "%" + query + "%";
        Cursor cursor = db.rawQuery("SELECT * FROM " + DBHelper.NOTE_TABLE + " WHERE content LIKE ?", new String[]{query});
        ArrayList<Note> res = fetchAllNote(cursor);
        cursor.close();
        db.close();
        return res;
    }

    public static ArrayList<Note> queryNoteFromDateRange(DBHelper helper, LocalDateTime startDate, LocalDateTime endDate) {

        Timestamp start = new Timestamp(startDate.toDateTime(DateTimeZone.UTC).getMillis());
        Timestamp end = new Timestamp(endDate.toDateTime(DateTimeZone.UTC).getMillis());
        return queryNoteFromDateRange(helper, start, end);

    }

    public static ArrayList<Note> queryNoteFromDateRange(DBHelper helper, Timestamp start, Timestamp end) {

        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + DBHelper.NOTE_TABLE + " WHERE updateTime >= ? and updateTime <= ? ",
                new String[]{String.valueOf(start.getTime()),
                        String.valueOf(end.getTime())
                });
        ArrayList<Note> res = fetchAllNote(cursor);
        cursor.close();
        db.close();
        return res;
    }

    public static ArrayList<Note> queryNoteFromCategory(DBHelper helper, int categoryId) {

        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM Note WHERE Note.category = ?",
                new String[]{String.valueOf(categoryId)});
        ArrayList<Note> res = fetchAllNote(cursor);
        cursor.close();
        db.close();
        return res;
    }

    private static ArrayList<Note> fetchAllNote(Cursor cursor) {
        ArrayList<Note> res = new ArrayList<>();
        if (cursor == null || !cursor.moveToFirst()) {
            return res;
        }
        while (!cursor.isAfterLast()) {
            res.add(DBHelper.getNoteFromCursor(cursor));
            cursor.moveToNext();
        }
        return res;
    }
}
